package gui;

import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.util.Enumeration;
import java.util.ListIterator;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.html.HTMLDocument.Iterator;

import javax.swing.JTextField;
import javax.swing.JLabel;

import Entity.User;
import controllers.OBLSettings;
import controllers.WelcomeUIP;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.SystemColor;
import javax.swing.ImageIcon;

import messagesPacks.*;

import ocsf.client.ObservableSWRClient;
import java.awt.Font;

public class WelcomeUI extends JFrame implements Observer
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	static WelcomeUI 		wui;
	private LoginUI 		 loginPanel = null;
	private WelcomeUIP		 welcomeUIP = null;
	private AdminUI 		 adminPanel = null;
	private SearchBooksUI 	 searchBookPanel = null ;
	private LibrarianUI 	 librarianPanel = null ; 
	private SubscriberUI     subscriberPanel = null ;
	private ManagerMainUI    managerMainUI=null;
	
	public static ActionListener 	exitActionL = null;
	public static ActionListener 	logoutActionL = null;
	
	private JPanel FirstPanel = null;
	private JButton btnConnect = null;
	private JTextField txtIP = null;;
	private JTextField txtPort;
	private boolean result_for_connection;
	

	// CONSTRUCTORS *********************************************************************************	
	/**
	 * This is the default constructor
	 */
	public WelcomeUI() 
	{
		super();
		wui = this;
		initialize();
	}
	//***********************************************************************************************
	/**
	 * This method initializes WelcomeUI Frame 
	 */
	private void initialize() 
	{
		
		this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");//setting the look and feel
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		this.setSize(OBLSettings.pane1Size[0], OBLSettings.pane1Size[1]);
		setResizable(false);
		setLocation(OBLSettings.frameLocation[0], OBLSettings.frameLocation[1]);
		this.setContentPane(getFirstPanel());
		this.setTitle("OBL System - Connection");
		
		this.welcomeUIP = new WelcomeUIP();
		this.welcomeUIP.getClient().addObserver(this);//welcomeUIP is now observing chatClient
		this.loginPanel = new LoginUI();
		this.searchBookPanel = new SearchBooksUI();
		
		
		this.setVisible( true ); // display frame
		
		logoutActionL = new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				if (welcomeUIP.logout() == 1) // Logout successful
				{
					switchPanel("OBL System - Login", loginPanel , OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
					loginPanel.setUser("");
					loginPanel.setPass("");				
					loginPanel.txtUser.grabFocus();
				}
				else	// Logout failure
				{
					JOptionPane.showMessageDialog( getWelcomeUI(), "Logout failed! ","Warning",JOptionPane.WARNING_MESSAGE);
				}
			}
		};

		exitActionL = new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				welcomeUIP.Exit(getWelcomeUI());
			}
		};
		// ============================================================================================
		//	     LoginUI Elements
		//		
		// back button loginPanel		
		loginPanel.btnBack.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				switchPanel("OBL System - Connection", FirstPanel , OBLSettings.pane1Size[0], OBLSettings.pane1Size[1]);
			}
		});		
		
		// login button loginPanel
		loginPanel.btnLogin.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e) 
			{
				String user = loginPanel.getUser();
				String Pass = loginPanel.getPass();
				
			 if(!user.isEmpty()  && !Pass.isEmpty())
			  {
				 LoginMessage logMsg = new LoginMessage();
				 logMsg = welcomeUIP.login(user,Pass);
				 
				 if(logMsg != null)
				 {
				    int login_result = logMsg.getLoginResult();	

					/**
					 * @author Roman
					 * @return values:
					 * 	   -1.Error in login
					 * 	   -2.user dosen't exist 
					 * 	   -3.wrong ID || wrong password
					 * 		0.user can be logged in
					 * 		1.already logged in
					 *  	2.user locked	
					 */
					
				    switch (login_result)
				    {
						case -3:
						{
						JOptionPane.showMessageDialog( getWelcomeUI(), "Wrong username or password ","Warning",JOptionPane.WARNING_MESSAGE);
						break;
						}
						case -2:
						{
						JOptionPane.showMessageDialog( getWelcomeUI(), "User dosen't exist","Warning",JOptionPane.WARNING_MESSAGE);
						break;
						}
						case -1:
						{
						JOptionPane.showMessageDialog( getWelcomeUI(), "Error in login","Error",JOptionPane.ERROR_MESSAGE);
						break;
						}
						case 1:
						{
						JOptionPane.showMessageDialog( getWelcomeUI(), "This user already logged in! ","Warning",JOptionPane.WARNING_MESSAGE);
						break;
						}
						case 2:
						{
						JOptionPane.showMessageDialog( getWelcomeUI(), "This user is locked ","Warning",JOptionPane.WARNING_MESSAGE);
						break;
						}
						case 0:
						{
						   int permmision = logMsg.getLoginPermmision();
						  // JOptionPane.showMessageDialog( getWelcomeUI(), "Welcome "+logMsg.getFname(),"Logged in succesfully",JOptionPane.PLAIN_MESSAGE);
						   switch (permmision)
						   {
						   	 case 1 ://Librarian Manager
						   	 {
						   		managerMainUI = new ManagerMainUI();
						   		managerMainUI.WelcomeLabel.setText("Welcome " + logMsg.getFname());
						   		managerMainUI.WelcomeLabel.setVisible(true);
								managerMainUI.btnExit.addActionListener(exitActionL);
								managerMainUI.btnLogout.addActionListener(logoutActionL);
								
								managerMainUI.managerViewEmployeesUI.btnLogout.addActionListener(logoutActionL);
								managerMainUI.managerViewEmployeesUI.btnExit.addActionListener(exitActionL);
								
								managerMainUI.managerSuspendSub.btnLogout.addActionListener(logoutActionL);
								managerMainUI.managerSuspendSub.btnExit.addActionListener(exitActionL);
								
								managerMainUI.managerBorrowReportUI.btnLogout.addActionListener(logoutActionL);
								managerMainUI.managerBorrowReportUI.btnExit.addActionListener(exitActionL);
								
								managerMainUI.managerActivityUI.btnLogout.addActionListener(logoutActionL);
								managerMainUI.managerActivityUI.btnExit.addActionListener(exitActionL);
								
								managerMainUI.managerLatenessReportUI.btnLogout.addActionListener(logoutActionL);
								managerMainUI.managerLatenessReportUI.btnExit.addActionListener(exitActionL);
								
								
						   		switchPanel("OBL System - Librarian Manager", managerMainUI , OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
						   		break;
						   	 }
						   	 case 2 ://Librarian
						   	 {
						   		librarianPanel = new LibrarianUI();
						   		librarianPanel.Welcome_label.setText("Welcome " + logMsg.getFname());
						   		
						 		librarianPanel.btnExit.addActionListener(exitActionL);
						 		librarianPanel.btnLogout.addActionListener(logoutActionL);	
						 				 		
						 		librarianPanel.librarianAddEditUserPanel.btnExitButton.addActionListener(exitActionL);
						 		librarianPanel.librarianAddEditUserPanel.btnLogoutButton.addActionListener(logoutActionL);
						 		
						 		librarianPanel.librarianSearchBookPanel.btnExit.addActionListener(exitActionL);
						 		librarianPanel.librarianSearchBookPanel.btnLogOut.addActionListener(logoutActionL);
						 		
						 		
						 		librarianPanel.librarianSearchBookPanel.librarianAddEditBookPanel.btnExitButton.addActionListener(exitActionL);
						 		librarianPanel.librarianSearchBookPanel.librarianAddEditBookPanel.btnLogoutButton.addActionListener(logoutActionL);
						 		
						 		librarianPanel.librarianAddEditBookPanel.btnExitButton.addActionListener(exitActionL);
						 		librarianPanel.librarianAddEditBookPanel.btnLogoutButton.addActionListener(logoutActionL);
						 		
						 		librarianPanel.librarianViewHistory.btnExitButton.addActionListener(exitActionL);
						 		librarianPanel.librarianViewHistory.btnLogoutButton.addActionListener(logoutActionL);
						 		
						 		librarianPanel.librarianAddEditCopyPanel.btnExitButton.addActionListener(exitActionL);
						 		librarianPanel.librarianAddEditCopyPanel.btnLogoutButton.addActionListener(logoutActionL);
						 		
						 		
						   		 switchPanel("OBL System - Librarian", librarianPanel , OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
						   		librarianPanel.textField.grabFocus();
						   		break;   
							 }
						   	 case 3 ://Subscriber reader
						   	 { 
						   		subscriberPanel = new SubscriberUI(); 
						   		subscriberPanel.subscriber = new User(logMsg.getUser() , logMsg.getPassword(),logMsg.getFname(), logMsg.getLname()
						   				,logMsg.getAddress() ,logMsg.getEmail() ,  logMsg.getPhone() ,logMsg.getLoginPermmision(), logMsg.getStatus() );
						   		subscriberPanel.lblWelcome.setText("Welcome "+ logMsg.getFname());	       
						   		subscriberPanel.btnLogout.addActionListener(logoutActionL) ;
							    subscriberPanel.btnExit.addActionListener(exitActionL) ;
							    
							    subscriberPanel.subEditProfilePanel.btnLogout.addActionListener(logoutActionL) ;
							    subscriberPanel.subEditProfilePanel.btnExit.addActionListener(exitActionL) ;
							    		
							    subscriberPanel.subSearchBookPanel.enableOrderButton = 1;
							    subscriberPanel.subSearchBookPanel.btnLogOut.addActionListener(logoutActionL);
							    subscriberPanel.subSearchBookPanel.btnExit.addActionListener(exitActionL);
							    
							    subscriberPanel.subViewHistoPanel.btnLogout.addActionListener(logoutActionL);
							    subscriberPanel.subViewHistoPanel.btnExit.addActionListener(exitActionL);
							    
							    subscriberPanel.subExtendPanel.btnLogOut.addActionListener(logoutActionL);
							    subscriberPanel.subExtendPanel.btnExit.addActionListener(exitActionL);
							    
						   		switchPanel("OBL System - Subscriber", subscriberPanel , OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
						   		break;
						   	 }
						   	 case 4 ://Administrator
						   	 {
						   		adminPanel = new AdminUI();
								adminPanel.btnLogout.addActionListener(logoutActionL);
								adminPanel.btnExit.addActionListener(exitActionL);
						   		switchPanel("OBL System - Administrator", adminPanel , OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
						   		break;
						   	 }
						   	 case 5 ://Subscriber Suspended
						   	 {
						   		subscriberPanel = new SubscriberUI(); 
						   		
						   		String ID = logMsg.getUser();
						   		String pass = logMsg.getPassword();
						   		String Fname =  logMsg.getFname();
						   		String Lname = logMsg.getLname();
						   		String adderrs = logMsg.getAddress() ;
						   		String email = logMsg.getEmail() ; 
						   		int permision = logMsg.getLoginPermmision();
						   		String phone = logMsg.getPhone();
						   		int stat = logMsg.getStatus();
						   		
						   		subscriberPanel.subscriber = new User(ID , pass, Fname , Lname ,adderrs , email , phone ,permmision, stat );
						   		
						   		subscriberPanel.lblWelcome.setText("Welcome "+ Fname);
						   		subscriberPanel.lblOblSubscriber.setText("OBL Suspended Subscriber");
						   		subscriberPanel.btnLogout.addActionListener(logoutActionL) ;
							    subscriberPanel.btnExit.addActionListener(exitActionL) ;
							    
							    subscriberPanel.subEditProfilePanel.btnLogout.addActionListener(logoutActionL) ;
							    subscriberPanel.subEditProfilePanel.btnExit.addActionListener(exitActionL) ;
							    subscriberPanel.subSearchBookPanel.enableOrderButton = 0;
							    subscriberPanel.subSearchBookPanel.cantOrderLabel.setText("you cannot order books because you are suspended ");
							    subscriberPanel.subSearchBookPanel.btnLogOut.addActionListener(logoutActionL);
							    subscriberPanel.subSearchBookPanel.btnExit.addActionListener(exitActionL);
							    
							    subscriberPanel.subViewHistoPanel.btnLogout.addActionListener(logoutActionL);
							    subscriberPanel.subViewHistoPanel.btnExit.addActionListener(exitActionL);
							    
							    subscriberPanel.btnExtendBorrow.setEnabled(false);

							    switchPanel("OBL System - Subscriber", subscriberPanel , OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
						   		
						   		break;
						   	 }
						   
						   }
						
						 break;
						}
					
				    }//switch
			   }//2nd if
				 else
				 JOptionPane.showMessageDialog( getWelcomeUI(), "An error occurred. Please try again.","Warning",JOptionPane.WARNING_MESSAGE); 
			 }//1st if
				else
				JOptionPane.showMessageDialog(getWelcomeUI(), "username or password field is empty","Warning",JOptionPane.WARNING_MESSAGE);

			}
		});
		
		// CheckBox to unveil the password in loginPanel
		loginPanel.chckbxShowPass.addItemListener(new ItemListener() 
		{
		    public void itemStateChanged(ItemEvent e) 
		    {
		        if (e.getStateChange() == ItemEvent.DESELECTED) 
		        {
		        	loginPanel.txtPassword.setEchoChar("\u25CF".toCharArray()[0]);
		        }
		        else 
		        {
		        	loginPanel.txtPassword.setEchoChar((char) 0);
		        }
		    }
		});
		//===========================================================================================
		//						SearchBooksUI Elements
		//============================================================================================	
			
		//search button in loginPanel		
		loginPanel.btnSearchBooks.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				searchBookPanel.loadAllsubjectsToSearchComboBox();
				switchPanel("OBL System - Search Books",searchBookPanel, OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
				searchBookPanel.searchByBookNameFiled.grabFocus();
			}
		});
		
		
		searchBookPanel.btnExitButton.addActionListener(exitActionL);
		
		txtIP.addActionListener(new ActionListener()
		{
	        public void actionPerformed(ActionEvent e)
	        {
	                btnConnect.doClick();
	        }  
	    });
		txtPort.addActionListener(new ActionListener()
		{
	        public void actionPerformed(ActionEvent e)
	        {
	                btnConnect.doClick();
	        }  
	    });

	}//initialize
	
	/**
	 * this method creating the first panel (connection panel)
	 * 
	 * @return first panel
	 */
	private JPanel getFirstPanel() 
	{
		if (FirstPanel == null)
		{
			FirstPanel = new JPanel();
			FirstPanel.setBackground(UIManager.getColor("Button.background"));
			FirstPanel.setToolTipText("");
			FirstPanel.setLayout(null);
			
			JLabel lblEnterTheIp = new JLabel("Enter the ip of the server and the designated port");
			lblEnterTheIp.setFont(new Font("Tahoma", Font.PLAIN, 13));
			lblEnterTheIp.setForeground(Color.BLACK);
			lblEnterTheIp.setBackground(SystemColor.text);
			lblEnterTheIp.setBounds(10, 8, 291, 34);
			FirstPanel.add(lblEnterTheIp);
			FirstPanel.add(getBtnConnect(), null);
			
			txtIP = new JTextField("localhost");
			txtIP.setFont(new Font("Tahoma", Font.PLAIN, 13));
			txtIP.setBounds(99, 53, 114, 20);
			FirstPanel.add(txtIP);
			txtIP.setColumns(10);
			
			txtPort = new JTextField("5555");
			txtPort.setFont(new Font("Tahoma", Font.PLAIN, 13));
			txtPort.setBounds(99, 88, 114, 20);
			FirstPanel.add(txtPort);
			txtPort.setColumns(10);
			
			JLabel lblIP = new JLabel("IP Address");
			lblIP.setFont(new Font("Tahoma", Font.PLAIN, 15));
			lblIP.setForeground(Color.BLACK);
			lblIP.setBounds(10, 50, 79, 23);
			FirstPanel.add(lblIP);
			
			JLabel lblPort = new JLabel("Port");
			lblPort.setFont(new Font("Tahoma", Font.PLAIN, 15));
			lblPort.setForeground(Color.BLACK);
			lblPort.setBounds(10, 88, 58, 17);
			FirstPanel.add(lblPort);
			
			JLabel label = new JLabel("");
			label.setIcon(OBLSettings.IMG_CLIENT_CONNECTION_BACKGROUND);
			label.setBounds(-14, 0, 455, 385);
			FirstPanel.add(label);
		}
		return FirstPanel; 
	}
//***********************************************************************************************	
	/**
	 * This method initializes ConnectButton	
	 */
	private JButton getBtnConnect() 
	{
		
		if (btnConnect == null) 
		{
			btnConnect = new JButton();
			btnConnect.setToolTipText("");
			btnConnect.setFont(new Font("Tahoma", Font.PLAIN, 15));
			btnConnect.setBounds(new Rectangle(99, 117, 92, 29));
			btnConnect.setText("Connect");
			btnConnect.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent e)
				{
					System.out.println("Connect button was pressed");
				// Handle IP & Port to WelcomeUIP
					result_for_connection = welcomeUIP.connect(getIP(), getPort());
					if (result_for_connection == false)
					{	// need to distinguish between server not running and bad ip or port
						System.out.println("Error: Can't setup connection!");
						JOptionPane.showMessageDialog( getWelcomeUI(), " server isn't running , check server ","Error on connection",JOptionPane.ERROR_MESSAGE);
					}
					else 
					{
					  //preparing the loginPanel ...
						System.out.println("Connecting..");
						loginPanel.setUser("");
						loginPanel.setPass("");
						loginPanel.chckbxShowPass.setSelected(false);
						switchPanel("OBL System - Login", loginPanel , OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);
						loginPanel.txtUser.grabFocus();
					}
				}
			});
		}
		
	
		return btnConnect;
	}
	
// ********************************** GETTERS & SETTERS ***************************************
	/**
	 * 
	 * @return ip of the server
	 */
	
	public String getIP()
	{
		String ipfield;
		try
		{
			ipfield = this.txtIP.getText();
		}
		catch(NullPointerException e)
		{
			return null;
		}
		if (ipfield.isEmpty()) return "localhost";
		return ipfield;
	}
	
//***********************************************************************************************	
	/**
	 * @return port of the server
	 */
	public String getPort()
	{
		String portfield;
		try
		{
			portfield = this.txtPort.getText();
		}
		catch(NullPointerException e)
		{
			return null;
		}
		if (portfield.isEmpty()) 
			return null;
	 return portfield;
	}
//***********************************************************************************************	
	/**
	 * 
	 * @return the main frame
	 */
	public WelcomeUI getWelcomeUI()
	{
		return wui; 
	}
//***********************************************************************************************
	/**
	 * 
	 * @return the WelcomeUIP
	 */
	public WelcomeUIP getWelcomeUIP()
	{
		return this.welcomeUIP;
	}
//***********************************************************************************************
	/**
	 * 
	 * @return the Login Panel
	 */
	public LoginUI getLoginPanel()
	{
		return this.loginPanel;
	}
//***********************************************************************************************	
	/**
	 * This method switches between panels
	 */
	public void switchPanel(String frameTitle , JPanel panelToSwitch,int width , int highet)
	{
		getWelcomeUI().setResizable(true);
		getWelcomeUI().setBounds(getWelcomeUI().getX() ,getWelcomeUI().getY() ,width, highet);
		getWelcomeUI().setResizable(false);
		setContentPane(panelToSwitch);
		getWelcomeUI().setTitle(frameTitle);
		System.out.println("Switched Panel");
	}	

//***********************************************************************************************
	@Override
	public void update(Observable arg0, Object arg1) 
	{
		System.out.println("UI: Recieved notify: arg0:   " + arg0.toString() + "   |   arg1: "+ arg1.toString());
		if (arg1 == ObservableSWRClient.CONNECTION_CLOSED)
		{
			System.out.printf("UI: Connection closed notify.");
			switchPanel("OBL System - Connection",getFirstPanel(),OBLSettings.pane1Size[0] , OBLSettings.pane1Size[1]);
			JOptionPane.showMessageDialog(getWelcomeUI(), " server was stopped ! ","Error on server",JOptionPane.ERROR_MESSAGE);
		}
	}


//***********************************************************************************************	
		/**
		 *  Main to create the main frame
		 */
		public static void main( String args[] )
		{ 
			WelcomeUI mainFrame = new WelcomeUI(); // create main frame

		} // end main
}//Class WelcomeUI

